package com.liyunc.demo.handler;

import com.liyunc.demo.enums.ResultCode;
import com.liyunc.demo.exception.DataAddException;
import com.liyunc.demo.exception.DataMatchException;
import com.liyunc.demo.exception.FromRepeatException;
import com.liyunc.demo.result.CommonResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * 全局异常拦截类.
 */
@Slf4j
@ControllerAdvice
@ResponseBody
public class GlobalExceptionHandler {
    /**
     * handle.
     */
    @ExceptionHandler(Exception.class)
    public CommonResult<ResultCode> handlerException(Exception exception) {
        if (exception instanceof DataAddException) {
            log.error("[全局异常拦截]DataAddException：请求方法{}，请求路径{}",
                ((DataAddException) exception).getCode(),
                exception.getMessage());
            return CommonResult.failed(ResultCode.DATA_ADD_ERROR);
        } else if (exception instanceof DataMatchException) {
            log.error("[全局异常拦截]DataMatchException：请求方法{}，请求路径{}",
                ((DataMatchException) exception).getCode(),
                exception.getMessage());
            return CommonResult.failed(ResultCode.USERNAME_OR_PASSWORD_ERROR);
        } else if (exception instanceof FromRepeatException) {
            log.error("[全局异常拦截]FromRepeatException：请求方法{}，请求路径{}",
                ((FromRepeatException) exception).getCode(),
                exception.getMessage());
            return CommonResult.failed(ResultCode.FROM_REPEAT_SUBMIT);
        } else {
            log.error("服务器内部出错{0}", exception);
            return CommonResult.failed(ResultCode.FAILED);
        }
    }
}
